//
//  SearchView.m
//  SearchView
//
//  Created by 冷悦 on 16/3/1.
//  Copyright © 2016年 冷悦. All rights reserved.
//

#import "CaculatePageSearchView.h"
#import "SearchViewIcon.h"
#import "UIView+Extension.h"

#ifndef kSearchViewPlaceHolderText
#define kSearchViewPlaceHolderText @"搜索房屋"
#endif

@interface CaculatePageSearchView() <SearchViewDelegate>

@property (nonatomic, strong)UITapGestureRecognizer *tapGestureRecognizer;

@property (nonatomic, strong)UILabel *placeHolderLabel;

@property (nonatomic, strong)SearchViewIcon *searchViewIcon;

@property (nonatomic, strong)UIView *containerView;

@property (nonatomic, assign)CGFloat storedWidth;

@end

@implementation CaculatePageSearchView

#pragma mark - Private
/**
 *  根据给定的size大小，计算label font的size
 *
 *  @param frameSize 给定的最大label size
 *
 *  @return 返回label的font大小与label的size
 */
- (NSArray *)caculateFontSize:(CGSize)frameSize{
    NSInteger currentFontSize = 17;
    NSString *placeHolder = self.placeHolder == nil ? kSearchViewPlaceHolderText : self.placeHolder;
    NSString *fontName = self.placeHolderLabel.font.fontName;
    CGSize requiredSize = [placeHolder boundingRectWithSize:frameSize
                                                    options:NSStringDrawingUsesFontLeading
                                                 attributes:@{NSFontAttributeName:[UIFont fontWithName:fontName size:currentFontSize]}
                                                    context:nil].size;
    
    if(requiredSize.height<=frameSize.height){
        
        while (requiredSize.height<=frameSize.height&&requiredSize.width<frameSize.width) {
            currentFontSize++;
            requiredSize=[placeHolder boundingRectWithSize:frameSize
                                                   options:NSStringDrawingUsesFontLeading
                                                attributes:@{NSFontAttributeName:[UIFont fontWithName:fontName size:currentFontSize]}
                                                   context:nil].size;
        }
    }else{
        while (requiredSize.height>frameSize.height||requiredSize.width>frameSize.width) {
            currentFontSize--;
            requiredSize=[placeHolder boundingRectWithSize:frameSize
                                                   options:NSStringDrawingUsesFontLeading
                                                attributes:@{NSFontAttributeName:[UIFont fontWithName:fontName size:currentFontSize]}
                                                   context:nil].size;
        }
        
        requiredSize=[placeHolder boundingRectWithSize:frameSize options:NSStringDrawingUsesFontLeading
                                            attributes:@{NSFontAttributeName:[UIFont fontWithName:fontName size:currentFontSize]}
                                               context:nil].size;
    }
    
    NSArray *result = @[@(currentFontSize), [NSValue valueWithCGSize:requiredSize]];
    
    return result;
}

- (void)setupContainerView:(CGRect)frame{
    CGFloat height = CGRectGetHeight(frame);
    CGFloat halfHeight = height / 2.0;
    CGFloat width = CGRectGetWidth(frame);
    CGPoint centerPoint = CGPointMake(CGRectGetWidth(frame) / 2.0, CGRectGetHeight(frame) / 2.0);
    self.containerView.height = halfHeight;
    NSArray *result = [self caculateFontSize:CGSizeMake(width - halfHeight, halfHeight)];
    NSInteger fontSize = [[result firstObject] integerValue];
    CGSize labelSize = [((NSValue *)[result lastObject]) CGSizeValue];
    CGFloat contentViewWidth;
    
    if (self.foldView == NO) {
        contentViewWidth = labelSize.width + halfHeight;
    } else {
        contentViewWidth = halfHeight;
    }
    
    self.containerView.width = contentViewWidth;
    self.containerView.center = centerPoint;
    self.placeHolderLabel.font = [UIFont fontWithName:self.placeHolderLabel.font.fontName size:fontSize];
    self.searchViewIcon.frame = CGRectMake(0, 0, halfHeight, halfHeight);
    self.placeHolderLabel.frame = CGRectMake(halfHeight, 0, labelSize.width, labelSize.height);
}


#pragma mark - Initalize
- (instancetype)init{
    self = [super init];
    self.userInteractionEnabled = YES;
    [self addSubview:self.containerView];
    return self;
}

#pragma mark - Response Events
- (void)tapAction:(UITapGestureRecognizer *)tapGestureRecognizer{
    if (self.delegate != nil && [self.delegate respondsToSelector:@selector(didTouchedView:)]){
        [self.delegate didTouchedView:self];
    }
}

#pragma mark - Override
- (void)setFrame:(CGRect)frame{
    [super setFrame:frame];
   DDLogInfo(@"folod:%@",NSStringFromCGRect(frame));
    CGFloat height = CGRectGetHeight(frame);
    self.storedWidth = CGRectGetWidth(frame);
    self.layer.masksToBounds = YES;
    self.layer.cornerRadius = height / 12.0;
    [self setupContainerView:frame];
}

#pragma mark - Setters
- (void)setDelegate:(id<SearchViewDelegate>)delegate{
    _delegate = delegate;
    NSArray *guestures = self.gestureRecognizers;
    
    if ([guestures containsObject:self.tapGestureRecognizer] == NO) {
        [self addGestureRecognizer:self.tapGestureRecognizer];
    }
}

- (void)setPlaceHolder:(NSString *)placeHolder{
    _placeHolder = placeHolder;
    self.placeHolderLabel.text = placeHolder;
}

- (void)setFoldView:(BOOL)foldView{
#ifndef kSearchViewAnimationDuration
#define kSearchViewAnimationDuration 0.2f
#endif
    _foldView = foldView;
    CGFloat animationDuration = self.animationDuration <= 0 ? kSearchViewAnimationDuration : self.animationDuration;
    
    if (foldView == YES) {
        [self.placeHolderLabel removeFromSuperview];
        [UIView animateWithDuration:animationDuration animations:^{
            CGFloat storedWidth = self.frame.size.width;
            self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.height, self.frame.size.height);
            self.storedWidth = storedWidth;
            self.layer.cornerRadius = self.frame.size.height / 2.0;
        }completion:^(BOOL finished) {
            self.searchViewIcon.shapeColor = [UIColor colorWithRed:52/255.0 green:152/255.0 blue:219/255.0 alpha:1.0];
            self.alpha = 0.8;
        }];
    } else {
        [UIView animateWithDuration:animationDuration animations:^{
            self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.storedWidth, self.frame.size.height);
            self.layer.cornerRadius = self.frame.size.height / 12.0;
        } completion:^(BOOL finished) {
            self.searchViewIcon.shapeColor = [UIColor colorWithRed:52/255.0 green:152/255.0 blue:219/255.0 alpha:1.0];
            [self.containerView addSubview:self.placeHolderLabel];
            self.alpha = 1.0;
        }];
    }
}

#pragma mark - Getters
- (UITapGestureRecognizer *)tapGestureRecognizer{
    if (_tapGestureRecognizer == nil) {
        _tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    }
    
    return _tapGestureRecognizer;
}

- (UIView *)containerView{
    if (_containerView == nil) {
        _containerView = [UIView new];
        [_containerView addSubview:self.placeHolderLabel];
        [_containerView addSubview:self.searchViewIcon];
    }
    
    return _containerView;
}

- (UILabel *)placeHolderLabel{
    if (_placeHolderLabel == nil) {
        _placeHolderLabel = [UILabel new];
        _placeHolderLabel.text = self.placeHolder == nil ? kSearchViewPlaceHolderText : self.placeHolder;
        _placeHolderLabel.textColor = [UIColor lightGrayColor];
        _placeHolderLabel.textAlignment = NSTextAlignmentCenter;
    }
    
    return _placeHolderLabel;
}

- (SearchViewIcon *)searchViewIcon{
    if (_searchViewIcon == nil) {
        _searchViewIcon = [SearchViewIcon new];
        _searchViewIcon.backgroundColor = [UIColor clearColor];
        _searchViewIcon.shapeColor = [UIColor colorWithRed:52/255.0 green:152/255.0 blue:219/255.0 alpha:1.0];
    }
    
    return _searchViewIcon;
}

@end
